<template>
    <el-form ref="ruleFormRef" style="width: 100%" :model="ruleForm" :rules="rules" label-width="auto" class="demo-ruleForm" :size="formSize" status-icon >
        <el-form-item label="权限设置" prop="auth">
            <el-tree ref="treeRef" style="max-width: 600px" :data="data" :default-checked-keys="checkedKeys" show-checkbox node-key="id" :props="defaultProps"/>
        </el-form-item>
        <div class="text-center">
            <el-button type="primary" @click="submitForm(ruleFormRef)" :loading="loading"> 保存 </el-button>
        </div>
    </el-form>
    <el-divider />
    
</template>
  
<script lang="ts" setup>
import { reactive, ref,watch } from 'vue'
import { ElMessage, type ComponentSize, type ElTree, type FormInstance, type FormRules } from 'element-plus'
import router from '../../../../router';
import http from '../../../../util/request';

let routerList:any = router.options.routes[0].children
let data:any = ref([])

const loading = ref<boolean>(false)
const checkedKeys:any = ref([])
const treeRef = ref<InstanceType<typeof ElTree>>()
const defaultProps = {
    children: 'children',
    label: 'label',
}

interface RuleForm {
    id:number
    user_id: number|string,
    auth:any
}

const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
const ruleForm = ref<RuleForm>({
    id:0,
    user_id: 0,
    auth:[],
})

const onGetRouter = () => {
    data.value = []
    routerList.forEach((e:any)=>{
        if(e.children){
            e.children = e.children.filter((item:any) => item.meta.is_show == true )
        }
        if(e.name != 'companys'){
            data.value.push(mapRouter(e))
            
        }
    })
}

const mapRouter = (rdata:any) => {
    rdata.id = rdata.name
    rdata.label = rdata.meta.side_name
    if(rdata.children){
        rdata.children.forEach((element:any) => {
            element.id = element.name
            element.label = element.meta.side_name
            if(element.children){
                mapRouter(element)
            }
        });
    }
    return rdata
}

const onGetData = () => {
    http.post('/user/auth',{user_id:ruleForm.value.user_id}).then((response:any)=>{
        if(response.data.data){
            ruleForm.value = response.data.data
            ruleForm.value.auth = response.data.data.auth ? JSON.parse(response.data.data.auth) : []
            checkedKeys.value = ruleForm.value.auth
        }
    })
}

const props = defineProps<{
    user_id:number|string,
}>()

watch(props,()=>{
    onGetRouter()
    ruleForm.value.user_id = props.user_id
    ruleForm.value.auth = []
    checkedKeys.value = []
    onGetData()
},{ immediate: true })

const rules = reactive<FormRules<RuleForm>>({
    auth: [
        { required: true, message: '请选择权限', trigger: 'blur' },
    ],
})

const submitForm = async (formEl: FormInstance | undefined) => {
    let auth:any = treeRef.value!.getCheckedKeys(false)
    // let authHal:any = treeRef.value!.getHalfCheckedKeys()
    ruleForm.value.auth = auth
    // auth.push(...authHal)
    ruleForm.value.auth = JSON.stringify(auth)
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            loading.value = true
            let request:any = null
            if(ruleForm.value.id){
                request = http.patch('/user/auth',ruleForm.value)
            }else{
                request = http.put('/user/auth',ruleForm.value)
            }
            request.then((response:any)=>{
                loading.value = false
                if(response.data.code != 200){
                    ElMessage.error(response.data.msg);
                    return
                }
                ElMessage.success(response.data.msg);
                onSave()
            })
            
        } else {
            console.log('error submit!', fields)
        }
    })
}

// const onRoleSelect = (data:number) => {
//     ruleForm.value.parent_id = data
// }

const onSave = () => {
    emit('onSave')
}

const emit = defineEmits(['onSave'])
</script>
<style scoped>
</style>
